var server = require('net').createServer();
var port = 3000;
var sockets = [];
server.on('listening', function(socket) {
    console.log("Server is listening on port", port);
});
server.on('close', function(socket) {
    console.log('server has new connection');
    socket.end();
    socket.close();
});
server.on('error', function() {
    console.log('Error occurred:', err.message);
});
server.on('connection', function(socket) {
    sockets.push(socket);
    console.log("got a new socket connection");
    bind(socket);
});
server.listen(port);

function bind(socket) {
    socket.on('data', function(data) {
        var response = anasy(socket, data);
        sockets.forEach(function(otherSocket) {
            // if (otherSocket !== socket) {
            otherSocket.write(response);
            // }
        });
    });
    socket.on('close', function() {
        console.log('connection closed');
        if (sockets.length > 0) {
            var index = sockets.indexOf(socket);
            sockets.splice(index, 1);
            console.log('sockets lendth:', sockets.length);
        }
    })
}

function anasy(socket, data) {
    //将data解析
    console.log(data);
    console.log(data.toString('utf8'));
    var anasyed = data.toString('utf8');
    console.log("socket address is ", socket.address());

    //协议解析
    var response = anasyed.split("").reverse().join("");
    //处理解析结果
    return response + '\n';
    //处理获取数据

    //返回处理结果
}
